<?php

namespace App\Http\Controllers;

use App\Http\Resources\Record as RecordResource;
use App\Models\Business;
use App\Models\Record;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Resources\User as UserResource;
use App\Http\Resources\People as PeopleResource;

class PeopleController extends Controller
{
    //
    public function index(Request $request){

        if($request->user_id == null){
            abort(404,'no user id!');
        }
        $data_cycle = data_cycles_from_date($request->date);

        if ($data_cycle['month']->greaterThan(Carbon::now())){
            abort(404, '日期错误');
        }

        $monthIds = Business::getBusinessIdByDataCycle('月');
        $quarterIds = Business::getBusinessIdByDataCycle('季度');
        $halfYearIds = Business::getBusinessIdByDataCycle('半年');
        $yearIds = Business::getBusinessIdByDataCycle('年');

        $monthRecords = User::find($request->user_id)->records()->whereIn('business_id',$monthIds)->whereDate('record_date',$data_cycle['month'])->get();
        $quarterRecords = User::find($request->user_id)->records()->whereIn('business_id',$quarterIds)->whereDate('record_date',$data_cycle['quarter'])->get();
        $halfYearRecords = User::find($request->user_id)->records()->whereIn('business_id',$halfYearIds)->whereDate('record_date',$data_cycle['half_year'])->get();
        $yearRecords = User::find($request->user_id)->records()->whereIn('business_id',$yearIds)->whereDate('record_date',$data_cycle['year'])->get();
        $records = $monthRecords->merge($quarterRecords)->merge($halfYearRecords)->merge($yearRecords);

        return RecordResource::collection($records);
    }

    public function search(Request $request){
        if ($request->keywords){
            $users =  User::where('name','like','%'.$request->keywords.'%')->get();
        } else {
            $users =  User::all();
        }
        return UserResource::collection($users);
    }

    public function info(Request $request)
    {
        if ( !$request->id){
            abort(404,'id不能为空');
            return;
        }
        $user = User::find($request->id);
        return new PeopleResource($user);

    }
}
